package com.bitbank.smartdevice.ui.base

import android.os.Bundle
import com.bitbank.smartdevice.ui.base.BaseFragment

/**
 *  Date：2018/12/12
 *  Author：xulee
 *  Desc：
 */
abstract class LazyFragment: BaseFragment() {

    private var isViewInitiated: Boolean = false //控件是否初始化完成
    private var isVisibleToUser: Boolean = false //页面是否可见
    private var isDataInitiated: Boolean = false //数据是否加载


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isVisibleToUser = isVisibleToUser
        prepareFetchData(false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        isViewInitiated = true
        prepareFetchData(false)
    }

    protected abstract fun loadData()

    private fun prepareFetchData(forceUpdate: Boolean) {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            loadData()
            isDataInitiated = true
        }
    }
}